package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"novels/models"
)

type Novelcontroller struct {
	beego.Controller
}

type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *Novelcontroller) Add() {
	name := c.GetString("name")
	title := c.GetString("title")
	num, _ := c.GetInt("num")

	novel := models.Novel{
		Name:  name,
		Title: title,
		Num:   num,
	}
	err := models.DB.Create(&novel).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *Novelcontroller) List() {
	var novel []models.Novel
	err := models.DB.Find(&novel).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: novel,
		}
		c.ServeJSON()

	}
}

func (c *Novelcontroller) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Novel{}, id).Error
	if err != nil {
		c.Data["josn"] = Res{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
